home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / mint / utilit~1 / futilsrc.zoo / fileutil / src / dir.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-10-21  |  37.4 KB  |  1,801 lines

  1. /* `dir', `vdir' and `ls' directory listing programs for GNU.
  2.    Copyright (C) 1985, 1988-1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* If the macro MULTI_COL is defined,
  19.    the multi-column format is the default regardless
  20.    of the type of output device.
  21.    This is for the `dir' program.
  22.  
  23.    If the macro LONG_FORMAT is defined,
  24.    the long format is the default regardless of the
  25.    type of output device.
  26.    This is for the `vdir' program.
  27.  
  28.    If neither is defined,
  29.    the output format depends on whether the output
  30.    device is a terminal.
  31.    This is for the `ls' program. */
  32.  
  33. /* Written by Richard Stallman and David MacKenzie. */
  34.  
  35. #ifdef _AIX
  36.  #pragma alloca
  37. #endif
  38. #include <sys/types.h>
  39. #ifndef _POSIX_SOURCE
  40. #include <sys/ioctl.h>
  41. #endif
  42. #include <stdio.h>
  43. #include <grp.h>
  44. #include <pwd.h>
  45. #include <getopt.h>
  46. #include <fnmatch.h>
  47. #include "system.h"
  48.  
  49. #ifndef S_IEXEC
  50. #define S_IEXEC S_IXUSR
  51. #endif
  52.  
  53. /* Return an int indicating the result of comparing two longs. */
  54. #ifdef INT_16_BITS
  55. #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
  56. #else
  57. #define longdiff(a, b) ((a) - (b))
  58. #endif
  59.  
  60. #ifdef STDC_HEADERS
  61. #include <time.h>
  62. #else
  63. char *ctime ();
  64. time_t time ();
  65. #endif
  66.  
  67. void mode_string ();
  68.  
  69. char *xstrdup ();
  70. char *getgroup ();
  71. char *getuser ();
  72. char *make_link_path ();
  73. char *xmalloc ();
  74. char *xrealloc ();
  75. int argmatch ();
  76. int compare_atime ();
  77. int rev_cmp_atime ();
  78. int compare_ctime ();
  79. int rev_cmp_ctime ();
  80. int compare_mtime ();
  81. int rev_cmp_mtime ();
  82. int compare_size ();
  83. int rev_cmp_size ();
  84. int compare_name ();
  85. int rev_cmp_name ();
  86. int compare_extension ();
  87. int rev_cmp_extension ();
  88. int decode_switches ();
  89. int file_interesting ();
  90. int gobble_file ();
  91. int is_not_dot_or_dotdot ();
  92. int length_of_file_name_and_frills ();
  93. void add_ignore_pattern ();
  94. void attach ();
  95. void clear_files ();
  96. void error ();
  97. void extract_dirs_from_files ();
  98. void get_link_name ();
  99. void indent ();
  100. void invalid_arg ();
  101. void print_current_files ();
  102. void print_dir ();
  103. void print_file_name_and_frills ();
  104. void print_horizontal ();
  105. void print_long_format ();
  106. void print_many_per_line ();
  107. void print_name_with_quoting ();
  108. void print_type_indicator ();
  109. void print_with_commas ();
  110. void queue_directory ();
  111. void sort_files ();
  112. void usage ();
  113.  
  114. enum filetype
  115. {
  116.   symbolic_link,
  117.   directory,
  118.   arg_directory,        /* Directory given as command line arg. */
  119.   normal            /* All others. */
  120. };
  121.  
  122. struct file
  123. {
  124.   /* The file name. */
  125.   char *name;
  126.  
  127.   struct stat stat;
  128.  
  129.   /* For symbolic link, name of the file linked to, otherwise zero. */
  130.   char *linkname;
  131.  
  132.   /* For symbolic link and long listing, st_mode of file linked to, otherwise
  133.      zero. */
  134.   unsigned int linkmode;
  135.  
  136.   enum filetype filetype;
  137. };
  138.  
  139. /* The table of files in the current directory:
  140.  
  141.    `files' points to a vector of `struct file', one per file.
  142.    `nfiles' is the number of elements space has been allocated for.
  143.    `files_index' is the number actually in use.  */
  144.  
  145. /* Address of block containing the files that are described.  */
  146.  
  147. struct file *files;
  148.  
  149. /* Length of block that `files' points to, measured in files.  */
  150.  
  151. int nfiles;
  152.  
  153. /* Index of first unused in `files'.  */
  154.  
  155. int files_index;
  156.  
  157. /* Record of one pending directory waiting to be listed.  */
  158.  
  159. struct pending
  160. {
  161.   char *name;
  162.   /* If the directory is actually the file pointed to by a symbolic link we
  163.      were told to list, `realname' will contain the name of the symbolic
  164.      link, otherwise zero. */
  165.   char *realname;
  166.   struct pending *next;
  167. };
  168.  
  169. struct pending *pending_dirs;
  170.  
  171. /* Current time (seconds since 1970).  When we are printing a file's time,
  172.    include the year if it is more than 6 months before this time.  */
  173.  
  174. time_t current_time;
  175.  
  176. /* The number of digits to use for block sizes.
  177.    4, or more if needed for bigger numbers.  */
  178.  
  179. int block_size_size;
  180.  
  181. /* The name the program was run with, stripped of any leading path. */
  182. char *program_name;
  183.  
  184. /* Option flags */
  185.  
  186. /* long_format for lots of info, one per line.
  187.    one_per_line for just names, one per line.
  188.    many_per_line for just names, many per line, sorted vertically.
  189.    horizontal for just names, many per line, sorted horizontally.
  190.    with_commas for just names, many per line, separated by commas.
  191.  
  192.    -l, -1, -C, -x and -m control this parameter.  */
  193.  
  194. enum format
  195. {
  196.   long_format,            /* -l */
  197.   one_per_line,            /* -1 */
  198.   many_per_line,        /* -C */
  199.   horizontal,            /* -x */
  200.   with_commas            /* -m */
  201. };
  202.  
  203. enum format format;
  204.  
  205. /* Type of time to print or sort by.  Controlled by -c and -u.  */
  206.  
  207. enum time_type
  208. {
  209.   time_mtime,            /* default */
  210.   time_ctime,            /* -c */
  211.   time_atime            /* -u */
  212. };
  213.  
  214. enum time_type time_type;
  215.  
  216. /* The file characteristic to sort by.  Controlled by -t, -S, -U, -X. */
  217.  
  218. enum sort_type
  219. {
  220.   sort_none,            /* -U */
  221.   sort_name,            /* default */
  222.   sort_extension,        /* -X */
  223.   sort_time,            /* -t */
  224.   sort_size            /* -S */
  225. };
  226.  
  227. enum sort_type sort_type;
  228.  
  229. /* Direction of sort.
  230.    0 means highest first if numeric,
  231.    lowest first if alphabetic;
  232.    these are the defaults.
  233.    1 means the opposite order in each case.  -r  */
  234.  
  235. int sort_reverse;
  236.  
  237. /* Nonzero means print the user and group id's as numbers rather
  238.    than as names.  -n  */
  239.  
  240. int numeric_users;
  241.  
  242. /* Nonzero means mention the size in 512 byte blocks of each file.  -s  */
  243.  
  244. int print_block_size;
  245.  
  246. /* Nonzero means show file sizes in kilobytes instead of blocks
  247.    (the size of which is system-dependant).  -k */
  248.  
  249. int kilobyte_blocks;
  250.  
  251. /* none means don't mention the type of files.
  252.    all means mention the types of all files.
  253.    not_programs means do so except for executables.
  254.  
  255.    Controlled by -F and -p.  */
  256.  
  257. enum indicator_style
  258. {
  259.   none,                /* default */
  260.   all,                /* -F */
  261.   not_programs            /* -p */
  262. };
  263.  
  264. enum indicator_style indicator_style;
  265.  
  266. /* Nonzero means mention the inode number of each file.  -i  */
  267.  
  268. int print_inode;
  269.  
  270. /* Nonzero means when a symbolic link is found, display info on
  271.    the file linked to.  -L  */
  272.  
  273. int trace_links;
  274.  
  275. /* Nonzero means when a directory is found, display info on its
  276.    contents.  -R  */
  277.  
  278. int trace_dirs;
  279.  
  280. /* Nonzero means when an argument is a directory name, display info
  281.    on it itself.  -d  */
  282.  
  283. int immediate_dirs;
  284.  
  285. /* Nonzero means don't omit files whose names start with `.'.  -A */
  286.  
  287. int all_files;
  288.  
  289. /* Nonzero means don't omit files `.' and `..'
  290.    This flag implies `all_files'.  -a  */
  291.  
  292. int really_all_files;
  293.  
  294. /* A linked list of shell-style globbing patterns.  If a non-argument
  295.    file name matches any of these patterns, it is omitted.
  296.    Controlled by -I.  Multiple -I options accumulate.
  297.    The -B option adds `*~' and `.*~' to this list.  */
  298.  
  299. struct ignore_pattern
  300. {
  301.   char *pattern;
  302.   struct ignore_pattern *next;
  303. };
  304.  
  305. struct ignore_pattern *ignore_patterns;
  306.  
  307. /* Nonzero means quote nongraphic chars in file names.  -b  */
  308.  
  309. int quote_funny_chars;
  310.  
  311. /* Nonzero means output nongraphic chars in file names as `?'.  -q  */
  312.  
  313. int qmark_funny_chars;
  314.  
  315. /* Nonzero means output each file name using C syntax for a string.
  316.    Always accompanied by `quote_funny_chars'.
  317.    This mode, together with -x or -C or -m,
  318.    and without such frills as -F or -s,
  319.    is guaranteed to make it possible for a program receiving
  320.    the output to tell exactly what file names are present.  -Q  */
  321.  
  322. int quote_as_string;
  323.  
  324. /* The number of chars per hardware tab stop.  -T */
  325. int tabsize;
  326.  
  327. /* Nonzero means we are listing the working directory because no
  328.    non-option arguments were given. */
  329.  
  330. int dir_defaulted;
  331.  
  332. /* Nonzero means print each directory name before listing it. */
  333.  
  334. int print_dir_name;
  335.  
  336. /* The line length to use for breaking lines in many-per-line format.
  337.    Can be set with -w.  */
  338.  
  339. int line_length;
  340.  
  341. /* If nonzero, the file listing format requires that stat be called on
  342.    each file. */
  343.  
  344. int format_needs_stat;
  345.  
  346. void
  347. main (argc, argv)
  348.      int argc;
  349.      char **argv;
  350. {
  351.   register int i;
  352.   register struct pending *thispend;
  353.  
  354.   dir_defaulted = 1;
  355.   print_dir_name = 1;
  356.   pending_dirs = 0;
  357.   current_time = time ((time_t *) 0);
  358.  
  359.   program_name = argv[0];
  360.   i = decode_switches (argc, argv);
  361.  
  362.   format_needs_stat = sort_type == sort_time || sort_type == sort_size
  363.     || format == long_format
  364.     || trace_links || trace_dirs || indicator_style != none
  365.     || print_block_size || print_inode;
  366.  
  367.   nfiles = 100;
  368.   files = (struct file *) xmalloc (sizeof (struct file) * nfiles);
  369.   files_index = 0;
  370.  
  371.   clear_files ();
  372.  
  373.   if (i < argc)
  374.     dir_defaulted = 0;
  375.   for (; i < argc; i++)
  376.     gobble_file (argv[i], 1, "");
  377.  
  378.   if (dir_defaulted)
  379.     {
  380.       if (immediate_dirs)
  381.     gobble_file (".", 1, "");
  382.       else
  383.     queue_directory (".", 0);
  384.     }
  385.  
  386.   if (files_index)
  387.     {
  388.       sort_files ();
  389.       if (!immediate_dirs)
  390.     extract_dirs_from_files ("", 0);
  391.       /* `files_index' might be zero now.  */
  392.     }
  393.   if (files_index)
  394.     {
  395.       print_current_files ();
  396.       if (pending_dirs)
  397.     putchar ('\n');
  398.     }
  399.   else if (pending_dirs && pending_dirs->next == 0)
  400.     print_dir_name = 0;
  401.  
  402.   while (pending_dirs)
  403.     {
  404.       thispend = pending_dirs;
  405.       pending_dirs = pending_dirs->next;
  406.       print_dir (thispend->name, thispend->realname);
  407.       free (thispend->name);
  408.       if (thispend->realname)
  409.     free (thispend->realname);
  410.       free (thispend);
  411.       print_dir_name = 1;
  412.     }
  413.  
  414.   exit (0);
  415. }
  416.  
  417. struct option long_options[] =
  418. {
  419.   {"all", 0, 0, 'a'},
  420.   {"escape", 0, 0, 'b'},
  421.   {"directory", 0, 0, 'd'},
  422.   {"inode", 0, 0, 'i'},
  423.   {"kilobytes", 0, 0, 'k'},
  424.   {"numeric-uid-gid", 0, 0, 'n'},
  425.   {"hide-control-chars", 0, 0, 'q'},
  426.   {"reverse", 0, 0, 'r'},
  427.   {"size", 0, 0, 's'},
  428.   {"width", 1, 0, 'w'},
  429.   {"almost-all", 0, 0, 'A'},
  430.   {"ignore-backups", 0, 0, 'B'},
  431.   {"classify", 0, 0, 'F'},
  432.   {"file-type", 0, 0, 'F'},
  433.   {"ignore", 1, 0, 'I'},
  434.   {"dereference", 0, 0, 'L'},
  435.   {"literal", 0, 0, 'N'},
  436.   {"quote-name", 0, 0, 'Q'},
  437.   {"recursive", 0, 0, 'R'},
  438.   {"format", 1, 0, 12},
  439.   {"sort", 1, 0, 10},
  440.   {"tabsize", 1, 0, 'T'},
  441.   {"time", 1, 0, 11},
  442.   {0, 0, 0, 0}
  443. };
  444.  
  445. char *format_args[] =
  446. {
  447.   "verbose", "long", "commas", "horizontal", "across",
  448.   "vertical", "single-column", 0
  449. };
  450.  
  451. enum format formats[] =
  452. {
  453.   long_format, long_format, with_commas, horizontal, horizontal,
  454.   many_per_line, one_per_line
  455. };
  456.  
  457. char *sort_args[] =
  458. {
  459.   "none", "time", "size", "extension", 0
  460. };
  461.  
  462. enum sort_type sort_types[] =
  463. {
  464.   sort_none, sort_time, sort_size, sort_extension
  465. };
  466.  
  467. char *time_args[] =
  468. {
  469.   "atime", "access", "use", "ctime", "status", 0
  470. };
  471.  
  472. enum time_type time_types[] =
  473. {
  474.   time_atime, time_atime, time_atime, time_ctime, time_ctime
  475. };
  476.  
  477. /* Set all the option flags according to the switches specified.
  478.    Return the index of the first non-option argument.  */
  479.  
  480. int
  481. decode_switches (argc, argv)
  482.      int argc;
  483.      char **argv;
  484. {
  485.   register char *p;
  486.   int c;
  487.   int i;
  488.  
  489.   qmark_funny_chars = 0;
  490.   quote_funny_chars = 0;
  491.  
  492.   /* initialize all switches to default settings */
  493.  
  494. #ifdef MULTI_COL
  495.   /* This is for the `dir' program.  */
  496.   format = many_per_line;
  497.   quote_funny_chars = 1;
  498. #else
  499. #ifdef LONG_FORMAT
  500.   /* This is for the `vdir' program.  */
  501.   format = long_format;
  502.   quote_funny_chars = 1;
  503. #else
  504.   /* This is for the `ls' program.  */
  505.   if (isatty (1))
  506.     {
  507.       format = many_per_line;
  508.       qmark_funny_chars = 1;
  509.     }
  510.   else
  511.     {
  512.       format = one_per_line;
  513.       qmark_funny_chars = 0;
  514.     }
  515. #endif
  516. #endif
  517.  
  518.   time_type = time_mtime;
  519.   sort_type = sort_name;
  520.   sort_reverse = 0;
  521.   numeric_users = 0;
  522.   print_block_size = 0;
  523.   kilobyte_blocks = getenv ("POSIX_ME_HARDER") == 0;
  524.   indicator_style = none;
  525.   print_inode = 0;
  526.   trace_links = 0;
  527.   trace_dirs = 0;
  528.   immediate_dirs = 0;
  529.   all_files = 0;
  530.   really_all_files = 0;
  531.   ignore_patterns = 0;
  532.   quote_as_string = 0;
  533.  
  534.   p = getenv ("COLUMNS");
  535.   line_length = p ? atoi (p) : 80;
  536.  
  537. #ifdef TIOCGWINSZ
  538.   {
  539.     struct winsize ws;
  540.  
  541.     if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
  542.       line_length = ws.ws_col;
  543.   }
  544. #endif
  545.  
  546.   p = getenv ("TABSIZE");
  547.   tabsize = p ? atoi (p) : 8;
  548.  
  549.   while ((c = getopt_long (argc, argv, "abcdgiklmnpqrstuw:xABCFI:LNQRST:UX1",
  550.                long_options, (int *) 0)) != EOF)
  551.     {
  552.       switch (c)
  553.     {
  554.     case 'a':
  555.       all_files = 1;
  556.       really_all_files = 1;
  557.       break;
  558.       
  559.     case 'b':
  560.       quote_funny_chars = 1;
  561.       qmark_funny_chars = 0;
  562.       break;
  563.       
  564.     case 'c':
  565.       time_type = time_ctime;
  566.       break;
  567.       
  568.     case 'd':
  569.       immediate_dirs = 1;
  570.       break;
  571.       
  572.     case 'g':
  573.       /* No effect.  For BSD compatibility. */
  574.       break;
  575.  
  576.     case 'i':
  577.       print_inode = 1;
  578.       break;
  579.       
  580.     case 'k':
  581.       kilobyte_blocks = 1;
  582.       break;
  583.       
  584.     case 'l':
  585.       format = long_format;
  586.       break;
  587.       
  588.     case 'm':
  589.       format = with_commas;
  590.       break;
  591.       
  592.     case 'n':
  593.       numeric_users = 1;
  594.       break;
  595.       
  596.     case 'p':
  597.       indicator_style = not_programs;
  598.       break;
  599.       
  600.     case 'q':
  601.       qmark_funny_chars = 1;
  602.       quote_funny_chars = 0;
  603.       break;
  604.       
  605.     case 'r':
  606.       sort_reverse = 1;
  607.       break;
  608.       
  609.     case 's':
  610.       print_block_size = 1;
  611.       break;
  612.       
  613.     case 't':
  614.       sort_type = sort_time;
  615.       break;
  616.       
  617.     case 'u':
  618.       time_type = time_atime;
  619.       break;
  620.       
  621.     case 'w':
  622.       line_length = atoi (optarg);
  623.       if (line_length < 1)
  624.         error (1, 0, "invalid line width: %s", optarg);
  625.       break;
  626.       
  627.     case 'x':
  628.       format = horizontal;
  629.       break;
  630.       
  631.     case 'A':
  632.       all_files = 1;
  633.       break;
  634.       
  635.     case 'B':
  636.       add_ignore_pattern ("*~");
  637.       add_ignore_pattern (".*~");
  638.       break;
  639.       
  640.     case 'C':
  641.       format = many_per_line;
  642.       break;
  643.       
  644.     case 'F':
  645.       indicator_style = all;
  646.       break;
  647.       
  648.     case 'I':
  649.       add_ignore_pattern (optarg);
  650.       break;
  651.       
  652.     case 'L':
  653.       trace_links = 1;
  654.       break;
  655.       
  656.     case 'N':
  657.       quote_funny_chars = 0;
  658.       qmark_funny_chars = 0;
  659.       break;
  660.       
  661.     case 'Q':
  662.       quote_as_string = 1;
  663.       quote_funny_chars = 1;
  664.       qmark_funny_chars = 0;
  665.       break;
  666.       
  667.     case 'R':
  668.       trace_dirs = 1;
  669.       break;
  670.       
  671.     case 'S':
  672.       sort_type = sort_size;
  673.       break;
  674.       
  675.     case 'T':
  676.       tabsize = atoi (optarg);
  677.       if (tabsize < 1)
  678.         error (1, 0, "invalid tab size: %s", optarg);
  679.       break;
  680.  
  681.     case 'U':
  682.       sort_type = sort_none;
  683.       break;
  684.  
  685.     case 'X':
  686.       sort_type = sort_extension;
  687.       break;
  688.  
  689.     case '1':
  690.       format = one_per_line;
  691.       break;
  692.       
  693.     case 10:        /* +sort */
  694.       i = argmatch (optarg, sort_args);
  695.       if (i < 0)
  696.         {
  697.           invalid_arg ("sort type", optarg, i);
  698.           usage ();
  699.         }
  700.       sort_type = sort_types[i];
  701.       break;
  702.  
  703.     case 11:        /* +time */
  704.       i = argmatch (optarg, time_args);
  705.       if (i < 0)
  706.         {
  707.           invalid_arg ("time type", optarg, i);
  708.           usage ();
  709.         }
  710.       time_type = time_types[i];
  711.       break;
  712.  
  713.     case 12:        /* +format */
  714.       i = argmatch (optarg, format_args);
  715.       if (i < 0)
  716.         {
  717.           invalid_arg ("format type", optarg, i);
  718.           usage ();
  719.         }
  720.       format = formats[i];
  721.       break;
  722.       
  723.     default:
  724.       usage ();
  725.     }
  726.     }
  727.  
  728.   return optind;
  729. }
  730.  
  731. /* Request that the directory named `name' have its contents listed later.
  732.    If `realname' is nonzero, it will be used instead of `name' when the
  733.    directory name is printed.  This allows symbolic links to directories
  734.    to be treated as regular directories but still be listed under their
  735.    real names. */
  736.  
  737. void
  738. queue_directory (name, realname)
  739.      char *name;
  740.      char *realname;
  741. {
  742.   struct pending *new;
  743.  
  744.   new = (struct pending *) xmalloc (sizeof (struct pending));
  745.   new->next = pending_dirs;
  746.   pending_dirs = new;
  747.   new->name = xstrdup (name);
  748.   if (realname)
  749.     new->realname = xstrdup (realname);
  750.   else
  751.     new->realname = 0;
  752. }
  753.  
  754. /* Read directory `name', and list the files in it.
  755.    If `realname' is nonzero, print its name instead of `name';
  756.    this is used for symbolic links to directories. */
  757.  
  758. void
  759. print_dir (name, realname)
  760.      char *name;
  761.      char *realname;
  762. {
  763.   register DIR *reading;
  764.   register struct direct *next;
  765.   register int total_blocks = 0;
  766.  
  767.   errno = 0;
  768.   reading = opendir (name);
  769.   if (!reading)
  770.     {
  771.       error (0, errno, "%s", name);
  772.       return;
  773.     }
  774.  
  775.   /* Read the directory entries, and insert the subfiles into the `files'
  776.      table.  */
  777.  
  778.   clear_files ();
  779.  
  780.   while (next = readdir (reading))
  781.     if (file_interesting (next))
  782.       total_blocks += gobble_file (next->d_name, 0, name);
  783.  
  784.   if (CLOSEDIR (reading))
  785.     {
  786.       error (0, errno, "%s", name);
  787.       /* Don't return; print whatever we got. */
  788.     }
  789.  
  790.   /* Sort the directory contents.  */
  791.   sort_files ();
  792.  
  793.   /* If any member files are subdirectories, perhaps they should have their
  794.      contents listed rather than being mentioned here as files.  */
  795.  
  796.   if (trace_dirs)
  797.     extract_dirs_from_files (name, 1);
  798.  
  799.   if (print_dir_name)
  800.     {
  801.       if (realname)
  802.     printf ("%s:\n", realname);
  803.       else
  804.     printf ("%s:\n", name);
  805.     }
  806.  
  807.   if (format == long_format || print_block_size)
  808.     printf ("total %u\n", total_blocks);
  809.  
  810.   if (files_index)
  811.     print_current_files ();
  812.  
  813.   if (pending_dirs)
  814.     putchar ('\n');
  815. }
  816.  
  817. /* Add `pattern' to the list of patterns for which files that match are
  818.    not listed.  */
  819.  
  820. void
  821. add_ignore_pattern (pattern)
  822.      char *pattern;
  823. {
  824.   register struct ignore_pattern *ignore;
  825.  
  826.   ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
  827.   ignore->pattern = pattern;
  828.   /* Add it to the head of the linked list. */
  829.   ignore->next = ignore_patterns;
  830.   ignore_patterns = ignore;
  831. }
  832.  
  833. /* Return nonzero if the file in `next' should be listed. */
  834.  
  835. int
  836. file_interesting (next)
  837.      register struct direct *next;
  838. {
  839.   register struct ignore_pattern *ignore;
  840.  
  841.   for (ignore = ignore_patterns; ignore; ignore = ignore->next)
  842.     if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
  843.       return 0;
  844.  
  845.   if (really_all_files
  846.       || next->d_name[0] != '.'
  847.       || (all_files
  848.       && next->d_name[1] != '\0'
  849.       && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
  850.     return 1;
  851.  
  852.   return 0;
  853. }
  854.  
  855. /* Enter and remove entries in the table `files'.  */
  856.  
  857. /* Empty the table of files. */
  858.  
  859. void
  860. clear_files ()
  861. {
  862.   register int i;
  863.  
  864.   for (i = 0; i < files_index; i++)
  865.     {
  866.       free (files[i].name);
  867.       if (files[i].linkname)
  868.     free (files[i].linkname);
  869.     }
  870.  
  871.   files_index = 0;
  872.   block_size_size = 4;
  873. }
  874.  
  875. /* Add a file to the current table of files.
  876.    Verify that the file exists, and print an error message if it does not.
  877.    Return the number of blocks that the file occupies.  */
  878.  
  879. int
  880. gobble_file (name, explicit_arg, dirname)
  881.      char *name;
  882.      int explicit_arg;
  883.      char *dirname;
  884. {
  885.   register int blocks;
  886.   register int val;
  887.   register char *path;
  888.  
  889.   if (files_index == nfiles)
  890.     {
  891.       nfiles *= 2;
  892.       files = (struct file *) xrealloc (files, sizeof (struct file) * nfiles);
  893.     }
  894.  
  895.   files[files_index].linkname = 0;
  896.   files[files_index].linkmode = 0;
  897.  
  898.   if (explicit_arg || format_needs_stat)
  899.     {
  900.       /* `path' is the absolute pathname of this file. */
  901.  
  902.       if (name[0] == '/' || dirname[0] == 0)
  903.     path = name;
  904.       else
  905.     {
  906.       path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
  907.       attach (path, dirname, name);
  908.     }
  909.  
  910.       if (trace_links)
  911.     {
  912.       val = stat (path, &files[files_index].stat);
  913.       if (val < 0)
  914.         /* Perhaps a symbolically-linked to file doesn't exist; stat
  915.            the link instead. */
  916.         val = lstat (path, &files[files_index].stat);
  917.     }
  918.       else
  919.     val = lstat (path, &files[files_index].stat);
  920.       if (val < 0)
  921.     {
  922.       error (0, errno, "%s", path);
  923.       return 0;
  924.     }
  925.  
  926. #ifdef S_ISLNK
  927.       if (S_ISLNK (files[files_index].stat.st_mode))
  928.     {
  929.       char *linkpath;
  930.       struct stat linkstats;
  931.  
  932.       get_link_name (path, &files[files_index]);
  933.       linkpath = make_link_path (path, files[files_index].linkname);
  934.  
  935.       /* Stat the file linked to; automatically trace it in non-long
  936.          listings, get its mode for the filetype indicator in long
  937.          listings. */
  938.       if (linkpath && lstat (linkpath, &linkstats) == 0)
  939.         {
  940.           if (S_ISDIR (linkstats.st_mode)
  941.           && explicit_arg && format != long_format)
  942.         {
  943.           char *tempname;
  944.  
  945.           /* Symbolic links to directories that are mentioned on the
  946.              command line are automatically traced if not being
  947.              listed as files. */
  948.           if (!immediate_dirs)
  949.             {
  950.               tempname = name;
  951.               name = linkpath;
  952.               linkpath = files[files_index].linkname;
  953.               files[files_index].linkname = tempname;
  954.             }
  955.           files[files_index].stat = linkstats;
  956.         }
  957.           else
  958.         files[files_index].linkmode = linkstats.st_mode;
  959.         }
  960.       if (linkpath)
  961.         free (linkpath);
  962.     }
  963. #endif
  964.  
  965. #ifdef S_ISLNK
  966.       if (S_ISLNK (files[files_index].stat.st_mode))
  967.     files[files_index].filetype = symbolic_link;
  968.       else
  969. #endif
  970.     if (S_ISDIR (files[files_index].stat.st_mode))
  971.       {
  972.         if (explicit_arg && !immediate_dirs)
  973.           files[files_index].filetype = arg_directory;
  974.         else
  975.           files[files_index].filetype = directory;
  976.       }
  977.     else
  978.       files[files_index].filetype = normal;
  979.  
  980.       blocks = convert_blocks (ST_NBLOCKS (files[files_index].stat),
  981.                    kilobyte_blocks);
  982.       if (blocks >= 10000 && block_size_size < 5)
  983.     block_size_size = 5;
  984.       if (blocks >= 100000 && block_size_size < 6)
  985.     block_size_size = 6;
  986.       if (blocks >= 1000000 && block_size_size < 7)
  987.     block_size_size = 7;
  988.     }
  989.   else
  990.     blocks = 0;
  991.  
  992.   files[files_index].name = xstrdup (name);
  993.   files_index++;
  994.  
  995.   return blocks;
  996. }
  997.  
  998. #ifdef S_ISLNK
  999.  
  1000. /* Put the name of the file that `filename' is a symbolic link to
  1001.    into the `linkname' field of `f'. */
  1002.  
  1003. void
  1004. get_link_name (filename, f)
  1005.      char *filename;
  1006.      struct file *f;
  1007. {
  1008.   register char *linkbuf;
  1009. #ifdef _AIX
  1010.   register int bufsiz = PATH_MAX; /* st_size is wrong. */
  1011. #else
  1012.   register int bufsiz = f->stat.st_size;
  1013. #endif
  1014.   register int linksize;
  1015.  
  1016.   linkbuf = (char *) xmalloc (bufsiz + 1);
  1017.   linksize = readlink (filename, linkbuf, bufsiz);
  1018.   if (linksize < 0)
  1019.     {
  1020.       error (0, errno, "%s", filename);
  1021.       free (linkbuf);
  1022.     }
  1023.   else
  1024.     {
  1025. #ifdef _AIX
  1026.       linkbuf = (char *) xrealloc (linkbuf, linksize + 1);
  1027. #endif
  1028.       linkbuf[linksize] = '\0';
  1029.       f->linkname = linkbuf;
  1030.     }
  1031. }
  1032.  
  1033. /* If `linkname' is a relative path and `path' contains one or more
  1034.    leading directories, return `linkname' with those directories
  1035.    prepended; otherwise, return a copy of `linkname'.
  1036.    If `linkname' is zero, return zero. */
  1037.  
  1038. char *
  1039. make_link_path (path, linkname)
  1040.      char *path;
  1041.      char *linkname;
  1042. {
  1043.   char *linkbuf;
  1044.   int bufsiz;
  1045.  
  1046.   if (linkname == 0)
  1047.     return 0;
  1048.  
  1049.   if (*linkname == '/')
  1050.     return xstrdup (linkname);
  1051.  
  1052.   /* The link is to a relative path.  Prepend any leading path
  1053.      in `path' to the link name. */
  1054.   linkbuf = rindex (path, '/');
  1055.   if (linkbuf == 0)
  1056.     return xstrdup (linkname);
  1057.  
  1058.   bufsiz = linkbuf - path + 1;
  1059.   linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
  1060.   strncpy (linkbuf, path, bufsiz);
  1061.   strcpy (linkbuf + bufsiz, linkname);
  1062.   return linkbuf;
  1063. }
  1064. #endif
  1065.  
  1066. /* Remove any entries from `files' that are for directories,
  1067.    and queue them to be listed as directories instead.
  1068.    `dirname' is the prefix to prepend to each dirname
  1069.    to make it correct relative to ls's working dir.
  1070.    `recursive' is nonzero if we should not treat `.' and `..' as dirs.
  1071.    This is desirable when processing directories recursively.  */
  1072.  
  1073. void
  1074. extract_dirs_from_files (dirname, recursive)
  1075.      char *dirname;
  1076.      int recursive;
  1077. {
  1078.   register int i, j;
  1079.   register char *path;
  1080.   int dirlen;
  1081.  
  1082.   dirlen = strlen (dirname) + 2;
  1083.   /* Queue the directories last one first, because queueing reverses the
  1084.      order.  */
  1085.   for (i = files_index - 1; i >= 0; i--)
  1086.     if ((files[i].filetype == directory || files[i].filetype == arg_directory)
  1087.     && (!recursive || is_not_dot_or_dotdot (files[i].name)))
  1088.       {
  1089.     if (files[i].name[0] == '/' || dirname[0] == 0)
  1090.       {
  1091.         queue_directory (files[i].name, files[i].linkname);
  1092.       }
  1093.     else
  1094.       {
  1095.         path = (char *) xmalloc (strlen (files[i].name) + dirlen);
  1096.         attach (path, dirname, files[i].name);
  1097.         queue_directory (path, files[i].linkname);
  1098.         free (path);
  1099.       }
  1100.     if (files[i].filetype == arg_directory)
  1101.       free (files[i].name);
  1102.       }
  1103.  
  1104.   /* Now delete the directories from the table, compacting all the remaining
  1105.      entries.  */
  1106.  
  1107.   for (i = 0, j = 0; i < files_index; i++)
  1108.     if (files[i].filetype != arg_directory)
  1109.       files[j++] = files[i];
  1110.   files_index = j;
  1111. }
  1112.  
  1113. /* Return non-zero if `name' doesn't end in `.' or `..'
  1114.    This is so we don't try to recurse on `././././. ...' */
  1115.  
  1116. int
  1117. is_not_dot_or_dotdot (name)
  1118.      char *name;
  1119. {
  1120.   char *t;
  1121.  
  1122.   t = rindex (name, '/');
  1123.   if (t)
  1124.     name = t + 1;
  1125.  
  1126.   if (name[0] == '.'
  1127.       && (name[1] == '\0'
  1128.       || (name[1] == '.' && name[2] == '\0')))
  1129.     return 0;
  1130.  
  1131.   return 1;
  1132. }
  1133.  
  1134. /* Sort the files now in the table.  */
  1135.  
  1136. void
  1137. sort_files ()
  1138. {
  1139.   int (*func) ();
  1140.  
  1141.   switch (sort_type)
  1142.     {
  1143.     case sort_none:
  1144.       return;
  1145.     case sort_time:
  1146.       switch (time_type)
  1147.     {
  1148.     case time_ctime:
  1149.       func = sort_reverse ? rev_cmp_ctime : compare_ctime;
  1150.       break;
  1151.     case time_mtime:
  1152.       func = sort_reverse ? rev_cmp_mtime : compare_mtime;
  1153.       break;
  1154.     case time_atime:
  1155.       func = sort_reverse ? rev_cmp_atime : compare_atime;
  1156.       break;
  1157.     }
  1158.       break;
  1159.     case sort_name:
  1160.       func = sort_reverse ? rev_cmp_name : compare_name;
  1161.       break;
  1162.     case sort_extension:
  1163.       func = sort_reverse ? rev_cmp_extension : compare_extension;
  1164.       break;
  1165.     case sort_size:
  1166.       func = sort_reverse ? rev_cmp_size : compare_size;
  1167.       break;
  1168.     }
  1169.  
  1170.   qsort (files, files_index, sizeof (struct file), func);
  1171. }
  1172.  
  1173. /* Comparison routines for sorting the files. */
  1174.  
  1175. int
  1176. compare_ctime (file1, file2)
  1177.      struct file *file1, *file2;
  1178. {
  1179.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1180. }
  1181.  
  1182. int
  1183. rev_cmp_ctime (file2, file1)
  1184.      struct file *file1, *file2;
  1185. {
  1186.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1187. }
  1188.  
  1189. int
  1190. compare_mtime (file1, file2)
  1191.      struct file *file1, *file2;
  1192. {
  1193.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1194. }
  1195.  
  1196. int
  1197. rev_cmp_mtime (file2, file1)
  1198.      struct file *file1, *file2;
  1199. {
  1200.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1201. }
  1202.  
  1203. int
  1204. compare_atime (file1, file2)
  1205.      struct file *file1, *file2;
  1206. {
  1207.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1208. }
  1209.  
  1210. int
  1211. rev_cmp_atime (file2, file1)
  1212.      struct file *file1, *file2;
  1213. {
  1214.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1215. }
  1216.  
  1217. int
  1218. compare_size (file1, file2)
  1219.      struct file *file1, *file2;
  1220. {
  1221.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1222. }
  1223.  
  1224. int
  1225. rev_cmp_size (file2, file1)
  1226.      struct file *file1, *file2;
  1227. {
  1228.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1229. }
  1230.  
  1231. int
  1232. compare_name (file1, file2)
  1233.      struct file *file1, *file2;
  1234. {
  1235.   return strcmp (file1->name, file2->name);
  1236. }
  1237.  
  1238. int
  1239. rev_cmp_name (file2, file1)
  1240.      struct file *file1, *file2;
  1241. {
  1242.   return strcmp (file1->name, file2->name);
  1243. }
  1244.  
  1245. /* Compare file extensions.  Files with no extension are `smallest'.
  1246.    If extensions are the same, compare by filenames instead. */
  1247.  
  1248. int
  1249. compare_extension (file1, file2)
  1250.      struct file *file1, *file2;
  1251. {
  1252.   register char *base1, *base2;
  1253.   register int cmp;
  1254.  
  1255.   base1 = rindex (file1->name, '.');
  1256.   base2 = rindex (file2->name, '.');
  1257.   if (base1 == 0 && base2 == 0)
  1258.     return strcmp (file1->name, file2->name);
  1259.   if (base1 == 0)
  1260.     return -1;
  1261.   if (base2 == 0)
  1262.     return 1;
  1263.   cmp = strcmp (base1, base2);
  1264.   if (cmp == 0)
  1265.     return strcmp (file1->name, file2->name);
  1266.   return cmp;
  1267. }
  1268.  
  1269. int
  1270. rev_cmp_extension (file2, file1)
  1271.      struct file *file1, *file2;
  1272. {
  1273.   register char *base1, *base2;
  1274.   register int cmp;
  1275.  
  1276.   base1 = rindex (file1->name, '.');
  1277.   base2 = rindex (file2->name, '.');
  1278.   if (base1 == 0 && base2 == 0)
  1279.     return strcmp (file1->name, file2->name);
  1280.   if (base1 == 0)
  1281.     return -1;
  1282.   if (base2 == 0)
  1283.     return 1;
  1284.   cmp = strcmp (base1, base2);
  1285.   if (cmp == 0)
  1286.     return strcmp (file1->name, file2->name);
  1287.   return cmp;
  1288. }
  1289.  
  1290. /* List all the files now in the table.  */
  1291.  
  1292. void
  1293. print_current_files ()
  1294. {
  1295.   register int i;
  1296.  
  1297.   switch (format)
  1298.     {
  1299.     case one_per_line:
  1300.       for (i = 0; i < files_index; i++)
  1301.     {
  1302.       print_file_name_and_frills (files + i);
  1303.       putchar ('\n');
  1304.     }
  1305.       break;
  1306.  
  1307.     case many_per_line:
  1308.       print_many_per_line ();
  1309.       break;
  1310.  
  1311.     case horizontal:
  1312.       print_horizontal ();
  1313.       break;
  1314.  
  1315.     case with_commas:
  1316.       print_with_commas ();
  1317.       break;
  1318.  
  1319.     case long_format:
  1320.       for (i = 0; i < files_index; i++)
  1321.     {
  1322.       print_long_format (files + i);
  1323.       putchar ('\n');
  1324.     }
  1325.       break;
  1326.     }
  1327. }
  1328.  
  1329. void
  1330. print_long_format (f)
  1331.      struct file *f;
  1332. {
  1333.   char modebuf[20];
  1334.   char timebuf[40];
  1335.   time_t when;
  1336.  
  1337.   mode_string (f->stat.st_mode, modebuf);
  1338.   modebuf[10] = 0;
  1339.  
  1340.   switch (time_type)
  1341.     {
  1342.     case time_ctime:
  1343.       when = f->stat.st_ctime;
  1344.       break;
  1345.     case time_mtime:
  1346.       when = f->stat.st_mtime;
  1347.       break;
  1348.     case time_atime:
  1349.       when = f->stat.st_atime;
  1350.       break;
  1351.     }
  1352.  
  1353.   strcpy (timebuf, ctime (&when));
  1354.   if (current_time - when > 6L * 30L * 24L * 60L * 60L
  1355.       || current_time - when < 0L)
  1356.     {
  1357.       /* The file is fairly old or in the future.
  1358.      POSIX says the cutoff is 6 months old;
  1359.      approximate this by 6*30 days.
  1360.      Show the year instead of the time of day.  */
  1361.       strcpy (timebuf + 11, timebuf + 19);
  1362.     }
  1363.   timebuf[16] = 0;
  1364.  
  1365.   if (print_inode)
  1366.     printf ("%6u ", f->stat.st_ino);
  1367.  
  1368.   if (print_block_size)
  1369.     printf ("%*u ", block_size_size,
  1370.         convert_blocks (ST_NBLOCKS (f->stat), kilobyte_blocks));
  1371.  
  1372.   /* The space between the mode and the number of links is the POSIX
  1373.      "optional alternate access method flag". */
  1374.   printf ("%s %3u ", modebuf, f->stat.st_nlink);
  1375.  
  1376.   if (numeric_users)
  1377.     printf ("%-8u ", (unsigned int) f->stat.st_uid);
  1378.   else
  1379.     printf ("%-8.8s ", getuser (f->stat.st_uid));
  1380.  
  1381.   if (numeric_users)
  1382.     printf ("%-8u ", (unsigned int) f->stat.st_gid);
  1383.   else
  1384.     printf ("%-8.8s ", getgroup (f->stat.st_gid));
  1385.  
  1386.   if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
  1387.     printf ("%3u, %3u ", major (f->stat.st_rdev),
  1388.         minor (f->stat.st_rdev));
  1389.   else
  1390.     printf ("%8lu ", f->stat.st_size);
  1391.  
  1392.   printf ("%s ", timebuf + 4);
  1393.  
  1394.   print_name_with_quoting (f->name);
  1395.  
  1396.   if (f->filetype == symbolic_link)
  1397.     {
  1398.       if (f->linkname)
  1399.     {
  1400.       fputs (" -> ", stdout);
  1401.       print_name_with_quoting (f->linkname);
  1402.       if (indicator_style != none)
  1403.         print_type_indicator (f->linkmode);
  1404.     }
  1405.     }
  1406.   else if (indicator_style != none)
  1407.     print_type_indicator (f->stat.st_mode);
  1408. }
  1409.  
  1410. void
  1411. print_name_with_quoting (p)
  1412.      register char *p;
  1413. {
  1414.   register unsigned char c;
  1415.  
  1416.   if (quote_as_string)
  1417.     putchar ('"');
  1418.  
  1419.   while (c = *p++)
  1420.     {
  1421.       if (quote_funny_chars)
  1422.     {
  1423.       switch (c)
  1424.         {
  1425.         case '\\':
  1426.           printf ("\\\\");
  1427.           break;
  1428.  
  1429.         case '\n':
  1430.           printf ("\\n");
  1431.           break;
  1432.  
  1433.         case '\b':
  1434.           printf ("\\b");
  1435.           break;
  1436.  
  1437.         case '\r':
  1438.           printf ("\\r");
  1439.           break;
  1440.  
  1441.         case '\t':
  1442.           printf ("\\t");
  1443.           break;
  1444.  
  1445.         case '\f':
  1446.           printf ("\\f");
  1447.           break;
  1448.  
  1449.         case ' ':
  1450.           printf ("\\ ");
  1451.           break;
  1452.  
  1453.         case '"':
  1454.           printf ("\\\"");
  1455.           break;
  1456.  
  1457.         default:
  1458.           if (c > 040 && c < 0177)
  1459.         putchar (c);
  1460.           else
  1461.         printf ("\\%03o", (unsigned int) c);
  1462.         }
  1463.     }
  1464.       else
  1465.     {
  1466.       if (c >= 040 && c < 0177)
  1467.         putchar (c);
  1468.       else if (!qmark_funny_chars)
  1469.         putchar (c);
  1470.       else
  1471.         putchar ('?');
  1472.     }
  1473.     }
  1474.  
  1475.   if (quote_as_string)
  1476.     putchar ('"');
  1477. }
  1478.  
  1479. /* Print the file name of `f' with appropriate quoting.
  1480.    Also print file size, inode number, and filetype indicator character,
  1481.    as requested by switches.  */
  1482.  
  1483. void
  1484. print_file_name_and_frills (f)
  1485.      struct file *f;
  1486. {
  1487.   if (print_inode)
  1488.     printf ("%6u ", f->stat.st_ino);
  1489.  
  1490.   if (print_block_size)
  1491.     printf ("%*u ", block_size_size,
  1492.         convert_blocks (ST_NBLOCKS (f->stat), kilobyte_blocks));
  1493.  
  1494.   print_name_with_quoting (f->name);
  1495.  
  1496.   if (indicator_style != none)
  1497.     print_type_indicator (f->stat.st_mode);
  1498. }
  1499.  
  1500. void
  1501. print_type_indicator (mode)
  1502.      unsigned int mode;
  1503. {
  1504.   if (S_ISDIR (mode))
  1505.     putchar ('/');
  1506.  
  1507. #ifdef S_ISLNK
  1508.   if (S_ISLNK (mode))
  1509.     putchar ('@');
  1510. #endif
  1511.  
  1512. #ifdef S_ISFIFO
  1513.   if (S_ISFIFO (mode))
  1514.     putchar ('|');
  1515. #endif
  1516.  
  1517. #ifdef S_ISSOCK
  1518.   if (S_ISSOCK (mode))
  1519.     putchar ('=');
  1520. #endif
  1521.  
  1522.   if (S_ISREG (mode) && indicator_style == all
  1523.       && (mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1524.     putchar ('*');
  1525. }
  1526.  
  1527. int
  1528. length_of_file_name_and_frills (f)
  1529.      struct file *f;
  1530. {
  1531.   register char *p = f->name;
  1532.   register char c;
  1533.   register int len = 0;
  1534.  
  1535.   if (print_inode)
  1536.     len += 7;
  1537.  
  1538.   if (print_block_size)
  1539.     len += 1 + block_size_size;
  1540.  
  1541.   if (quote_as_string)
  1542.     len += 2;
  1543.  
  1544.   while (c = *p++)
  1545.     {
  1546.       if (quote_funny_chars)
  1547.     {
  1548.       switch (c)
  1549.         {
  1550.         case '\\':
  1551.         case '\n':
  1552.         case '\b':
  1553.         case '\r':
  1554.         case '\t':
  1555.         case '\f':
  1556.         case ' ':
  1557.           len += 2;
  1558.           break;
  1559.  
  1560.         case '"':
  1561.           if (quote_as_string)
  1562.         len += 2;
  1563.           else
  1564.         len += 1;
  1565.           break;
  1566.  
  1567.         default:
  1568.           if (c >= 040 && c < 0177)
  1569.         len += 1;
  1570.           else
  1571.         len += 4;
  1572.         }
  1573.     }
  1574.       else
  1575.     len += 1;
  1576.     }
  1577.  
  1578.   if (indicator_style != none)
  1579.     {
  1580.       unsigned filetype = f->stat.st_mode;
  1581.  
  1582.       if (S_ISREG (filetype))
  1583.     {
  1584.       if (indicator_style == all
  1585.           && (f->stat.st_mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1586.         len += 1;
  1587.     }
  1588.       else if (S_ISDIR (filetype)
  1589. #ifdef S_ISLNK
  1590.            || S_ISLNK (filetype)
  1591. #endif
  1592. #ifdef S_ISFIFO
  1593.            || S_ISFIFO (filetype)
  1594. #endif
  1595. #ifdef S_ISSOCK
  1596.            || S_ISSOCK (filetype)
  1597. #endif
  1598.            )
  1599.     len += 1;
  1600.     }
  1601.  
  1602.   return len;
  1603. }
  1604.  
  1605. void
  1606. print_many_per_line ()
  1607. {
  1608.   int filesno;            /* Index into files. */
  1609.   int row;            /* Current row. */
  1610.   int max_name_length;        /* Length of longest file name + frills. */
  1611.   int name_length;        /* Length of each file name + frills. */
  1612.   int pos;            /* Current character column. */
  1613.   int cols;            /* Number of files across. */
  1614.   int rows;            /* Maximum number of files down. */
  1615.  
  1616.   /* Compute the maximum file name length.  */
  1617.   max_name_length = 0;
  1618.   for (filesno = 0; filesno < files_index; filesno++)
  1619.     {
  1620.       name_length = length_of_file_name_and_frills (files + filesno);
  1621.       if (name_length > max_name_length)
  1622.     max_name_length = name_length;
  1623.     }
  1624.  
  1625.   /* Allow at least two spaces between names.  */
  1626.   max_name_length += 2;
  1627.  
  1628.   /* Calculate the maximum number of columns that will fit. */
  1629.   cols = line_length / max_name_length;
  1630.   if (cols == 0)
  1631.     cols = 1;
  1632.   /* Calculate the number of rows that will be in each column except possibly
  1633.      for a short column on the right. */
  1634.   rows = files_index / cols + (files_index % cols != 0);
  1635.   /* Recalculate columns based on rows. */
  1636.   cols = files_index / rows + (files_index % rows != 0);
  1637.  
  1638.   for (row = 0; row < rows; row++)
  1639.     {
  1640.       filesno = row;
  1641.       pos = 0;
  1642.       /* Print the next row.  */
  1643.       while (1)
  1644.     {
  1645.       print_file_name_and_frills (files + filesno);
  1646.       name_length = length_of_file_name_and_frills (files + filesno);
  1647.  
  1648.       filesno += rows;
  1649.       if (filesno >= files_index)
  1650.         break;
  1651.  
  1652.       indent (pos + name_length, pos + max_name_length);
  1653.       pos += max_name_length;
  1654.     }
  1655.       putchar ('\n');
  1656.     }
  1657. }
  1658.  
  1659. void
  1660. print_horizontal ()
  1661. {
  1662.   int filesno;
  1663.   int max_name_length;
  1664.   int name_length;
  1665.   int cols;
  1666.   int pos;
  1667.  
  1668.   /* Compute the maximum file name length.  */
  1669.   max_name_length = 0;
  1670.   for (filesno = 0; filesno < files_index; filesno++)
  1671.     {
  1672.       name_length = length_of_file_name_and_frills (files + filesno);
  1673.       if (name_length > max_name_length)
  1674.     max_name_length = name_length;
  1675.     }
  1676.  
  1677.   /* Allow two spaces between names.  */
  1678.   max_name_length += 2;
  1679.  
  1680.   cols = line_length / max_name_length;
  1681.   if (cols == 0)
  1682.     cols = 1;
  1683.  
  1684.   pos = 0;
  1685.   name_length = 0;
  1686.  
  1687.   for (filesno = 0; filesno < files_index; filesno++)
  1688.     {
  1689.       if (filesno != 0)
  1690.     {
  1691.       if (filesno % cols == 0)
  1692.         {
  1693.           putchar ('\n');
  1694.           pos = 0;
  1695.         }
  1696.       else
  1697.         {
  1698.           indent (pos + name_length, pos + max_name_length);
  1699.           pos += max_name_length;
  1700.         }
  1701.     }
  1702.  
  1703.       print_file_name_and_frills (files + filesno);
  1704.  
  1705.       name_length = length_of_file_name_and_frills (files + filesno);
  1706.     }
  1707.   putchar ('\n');
  1708. }
  1709.  
  1710. void
  1711. print_with_commas ()
  1712. {
  1713.   int filesno;
  1714.   int pos, old_pos;
  1715.  
  1716.   pos = 0;
  1717.  
  1718.   for (filesno = 0; filesno < files_index; filesno++)
  1719.     {
  1720.       old_pos = pos;
  1721.  
  1722.       pos += length_of_file_name_and_frills (files + filesno);
  1723.       if (filesno + 1 < files_index)
  1724.     pos += 2;        /* For the comma and space */
  1725.  
  1726.       if (old_pos != 0 && pos >= line_length)
  1727.     {
  1728.       putchar ('\n');
  1729.       pos -= old_pos;
  1730.     }
  1731.  
  1732.       print_file_name_and_frills (files + filesno);
  1733.       if (filesno + 1 < files_index)
  1734.     {
  1735.       putchar (',');
  1736.       putchar (' ');
  1737.     }
  1738.     }
  1739.   putchar ('\n');
  1740. }
  1741.  
  1742. /* Assuming cursor is at position FROM, indent up to position TO.  */
  1743.  
  1744. void
  1745. indent (from, to)
  1746.      int from, to;
  1747. {
  1748.   while (from < to)
  1749.     {
  1750.       if (to / tabsize > from / tabsize)
  1751.     {
  1752.       putchar ('\t');
  1753.       from += tabsize - from % tabsize;
  1754.     }
  1755.       else
  1756.     {
  1757.       putchar (' ');
  1758.       from++;
  1759.     }
  1760.     }
  1761. }
  1762.  
  1763. /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
  1764.  
  1765. void
  1766. attach (dest, dirname, name)
  1767.      char *dest, *dirname, *name;
  1768. {
  1769.   char *dirnamep = dirname;
  1770.  
  1771.   /* Copy dirname if it is not ".". */
  1772.   if (dirname[0] != '.' || dirname[1] != 0)
  1773.     {
  1774.       while (*dirnamep)
  1775.     *dest++ = *dirnamep++;
  1776.       /* Add '/' if `dirname' doesn't already end with it. */
  1777.       if (dirnamep > dirname && dirnamep[-1] != '/')
  1778.     *dest++ = '/';
  1779.     }
  1780.   while (*name)
  1781.     *dest++ = *name++;
  1782.   *dest = 0;
  1783. }
  1784.  
  1785. void
  1786. usage ()
  1787. {
  1788.   fprintf (stderr, "\
  1789. Usage: %s [-abcdgiklmnpqrstuxABCFLNQRSUX1] [-w cols] [-T cols] [-I pattern]\n\
  1790.        [+all] [+escape] [+directory] [+inode] [+kilobytes]\n\
  1791.        [+numeric-uid-gid] [+hide-control-chars] [+reverse] [+size]\n\
  1792.        [+width=cols] [+tabsize=cols] [+almost-all] [+ignore-backups]\n",
  1793.        program_name);
  1794.   fprintf (stderr, "\
  1795.        [+classify] [+file-type] [+ignore=pattern] [+dereference] [+literal]\n\
  1796.        [+quote-name] [+recursive] [+sort={none,time,size,extension}]\n\
  1797.        [+format={long,verbose,commas,across,vertical,single-column}]\n\
  1798.        [+time={atime,access,use,ctime,status}] [path...]\n");
  1799.   exit (1);
  1800. }
  1801.